<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>管理员主界面 - 待办事项管理系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: #f8f9fa;
            min-height: 100vh;
        }

        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px 0;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        .header-content {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .header h1 {
            font-size: 24px;
            font-weight: 600;
        }

        .admin-info {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .admin-name {
            font-weight: 500;
        }

        .logout-btn {
            background: rgba(255,255,255,0.2);
            color: white;
            border: 1px solid rgba(255,255,255,0.3);
            padding: 8px 16px;
            border-radius: 5px;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .logout-btn:hover {
            background: rgba(255,255,255,0.3);
        }

        .main-content {
            max-width: 1200px;
            margin: 30px auto;
            padding: 0 20px;
        }

        .dashboard {
            display: grid;
            grid-template-columns: 1fr 1fr 1fr 1fr;
            gap: 20px;
            margin-bottom: 30px;
        }

        .stat-card {
            background: white;
            padding: 25px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            text-align: center;
        }

        .stat-number {
            font-size: 36px;
            font-weight: bold;
            color: #667eea;
            margin-bottom: 10px;
        }

        .stat-label {
            color: #666;
            font-size: 14px;
        }

        .nav-tabs {
            display: flex;
            background: white;
            border-radius: 10px 10px 0 0;
            overflow: hidden;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        .nav-tab {
            flex: 1;
            padding: 15px 20px;
            background: #f8f9fa;
            border: none;
            cursor: pointer;
            font-weight: 500;
            color: #666;
            transition: all 0.3s ease;
        }

        .nav-tab.active {
            background: #667eea;
            color: white;
        }

        .tab-content {
            background: white;
            border-radius: 0 0 10px 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            overflow: hidden;
        }

        .tab-pane {
            display: none;
            padding: 20px;
        }

        .tab-pane.active {
            display: block;
        }

        .section-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid #e9ecef;
        }

        .section-header h2 {
            color: #333;
            font-size: 20px;
        }

        .add-btn {
            background: #667eea;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            font-weight: 500;
            transition: background 0.3s ease;
        }

        .add-btn:hover {
            background: #5a6fd8;
        }

        .data-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }

        .data-table th,
        .data-table td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #e9ecef;
        }

        .data-table th {
            background: #f8f9fa;
            font-weight: 600;
            color: #333;
        }

        .data-table tr:hover {
            background: #f8f9fa;
        }

        .action-btn {
            padding: 5px 10px;
            border: none;
            border-radius: 3px;
            cursor: pointer;
            font-size: 12px;
            margin-right: 5px;
            transition: all 0.3s ease;
        }

        .edit-btn {
            background: #ffc107;
            color: #212529;
        }

        .edit-btn:hover {
            background: #e0a800;
        }

        .delete-btn {
            background: #dc3545;
            color: white;
        }

        .delete-btn:hover {
            background: #c82333;
        }

        .status-badge {
            padding: 3px 8px;
            border-radius: 12px;
            font-size: 11px;
            font-weight: 500;
        }

        .status-pending {
            background: #fff3cd;
            color: #856404;
        }

        .status-completed {
            background: #d4edda;
            color: #155724;
        }

        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
        }

        .modal-content {
            background-color: white;
            margin: 5% auto;
            padding: 30px;
            border-radius: 10px;
            width: 90%;
            max-width: 500px;
            position: relative;
        }

        .close {
            position: absolute;
            right: 20px;
            top: 15px;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
            color: #aaa;
        }

        .close:hover {
            color: #000;
        }

        .modal h2 {
            margin-bottom: 20px;
            color: #333;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: #333;
        }

        .form-group input,
        .form-group select {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
        }

        .modal-actions {
            display: flex;
            gap: 10px;
            justify-content: flex-end;
        }

        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-weight: 500;
            transition: all 0.3s ease;
        }

        .btn-primary {
            background: #667eea;
            color: white;
        }

        .btn-primary:hover {
            background: #5a6fd8;
        }

        .btn-secondary {
            background: #6c757d;
            color: white;
        }

        .btn-secondary:hover {
            background: #5a6268;
        }

        .search-filter {
            display: flex;
            gap: 15px;
            margin-bottom: 20px;
            align-items: center;
            flex-wrap: wrap;
        }

        .search-input {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
            min-width: 200px;
        }

        .filter-select {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
        }

        @media (max-width: 768px) {
            .dashboard {
                grid-template-columns: 1fr 1fr;
            }

            .nav-tabs {
                flex-direction: column;
            }

            .search-filter {
                flex-direction: column;
                align-items: stretch;
            }

            .data-table {
                font-size: 12px;
            }

            .data-table th,
            .data-table td {
                padding: 8px;
            }
        }
    </style>
</head>
<body>
<div class="header">
    <div class="header-content">
        <h1>管理员控制台</h1>
        <div class="admin-info">
            <span class="admin-name" id="adminName">欢迎，管理员</span>
            <button class="logout-btn" onclick="logout()">退出登录</button>
        </div>
    </div>
</div>

<div class="main-content">
    <div class="dashboard">
        <div class="stat-card">
            <div class="stat-number" id="totalUsers">0</div>
            <div class="stat-label">总用户数</div>
        </div>
        <div class="stat-card">
            <div class="stat-number" id="totalTodos">0</div>
            <div class="stat-label">总待办事项</div>
        </div>
        <div class="stat-card">
            <div class="stat-number" id="pendingTodos">0</div>
            <div class="stat-label">待完成事项</div>
        </div>
        <div class="stat-card">
            <div class="stat-number" id="totalAdmins">0</div>
            <div class="stat-label">管理员数量</div>
        </div>
    </div>

    <div class="nav-tabs">
        <button class="nav-tab active" onclick="switchTab('users')">用户管理</button>
        <button class="nav-tab" onclick="switchTab('todos')">待办事项管理</button>
        <button class="nav-tab" onclick="switchTab('admins')">管理员管理</button>
    </div>

    <div class="tab-content">
        <!-- 用户管理 -->
        <div id="users" class="tab-pane active">
            <div class="section-header">
                <h2>用户管理</h2>
                <button class="add-btn" onclick="openUserModal()">添加用户</button>
            </div>

            <div class="search-filter">
                <input type="text" id="userSearch" class="search-input" placeholder="搜索用户..." oninput="filterUsers()">
            </div>

            <table class="data-table" id="userTable">
                <thead>
                <tr>
                    <th>用户ID</th>
                    <th>用户名</th>
                    <th>注册时间</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody id="userTableBody">
                <!-- 用户数据将在这里动态生成 -->
                </tbody>
            </table>
        </div>

        <!-- 待办事项管理 -->
        <div id="todos" class="tab-pane">
            <div class="section-header">
                <h2>待办事项管理</h2>
            </div>

            <div class="search-filter">
                <input type="text" id="todoSearch" class="search-input" placeholder="搜索待办事项..." oninput="filterTodos()">
                <select id="todoStatusFilter" class="filter-select" onchange="filterTodos()">
                    <option value="">全部状态</option>
                    <option value="未完成">未完成</option>
                    <option value="已完成">已完成</option>
                </select>
            </div>

            <table class="data-table" id="todoTable">
                <thead>
                <tr>
                    <th>事项ID</th>
                    <th>标题</th>
                    <th>内容</th>
                    <th>状态</th>
                    <th>用户</th>
                    <th>创建时间</th>
                    <th>截止时间</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody id="todoTableBody">
                <!-- 待办事项数据将在这里动态生成 -->
                </tbody>
            </table>
        </div>

        <!-- 管理员管理 -->
        <div id="admins" class="tab-pane">
            <div class="section-header">
                <h2>管理员管理</h2>
                <button class="add-btn" onclick="openAdminModal()">添加管理员</button>
            </div>

            <table class="data-table" id="adminTable">
                <thead>
                <tr>
                    <th>管理员ID</th>
                    <th>管理员名</th>
                    <th>创建时间</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody id="adminTableBody">
                <!-- 管理员数据将在这里动态生成 -->
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- 用户模态框 -->
<div id="userModal" class="modal">
    <div class="modal-content">
        <span class="close" onclick="closeUserModal()">&times;</span>
        <h2 id="userModalTitle">添加用户</h2>
        <form id="userForm">
            <div class="form-group">
                <label for="username">用户名</label>
                <input type="text" id="username" required>
            </div>
            <div class="form-group">
                <label for="password">密码</label>
                <input type="password" id="password" required>
            </div>
            <div class="modal-actions">
                <button type="button" class="btn btn-secondary" onclick="closeUserModal()">取消</button>
                <button type="submit" class="btn btn-primary">保存</button>
            </div>
        </form>
    </div>
</div>

<!-- 管理员模态框 -->
<div id="adminModal" class="modal">
    <div class="modal-content">
        <span class="close" onclick="closeAdminModal()">&times;</span>
        <h2 id="adminModalTitle">添加管理员</h2>
        <form id="adminForm">
            <div class="form-group">
                <label for="adminName">管理员名</label>
                <input type="text" id="adminNameInput" required>
            </div>
            <div class="form-group">
                <label for="adminPassword">密码</label>
                <input type="password" id="adminPassword" required>
            </div>
            <div class="modal-actions">
                <button type="button" class="btn btn-secondary" onclick="closeAdminModal()">取消</button>
                <button type="submit" class="btn btn-primary">保存</button>
            </div>
        </form>
    </div>
</div>

<!-- 新增：待办事项编辑模态框 -->
<div id="todoModal" class="modal">
  <div class="modal-content">
    <span class="close" onclick="closeTodoModal()">&times;</span>
    <h2 id="todoModalTitle">编辑待办事项</h2>
    <form id="todoForm">
      <div class="form-group">
        <label for="todoTitle">标题</label>
        <input type="text" id="todoTitle" required>
      </div>
      <div class="form-group">
        <label for="todoContent">内容</label>
        <input type="text" id="todoContent" required>
      </div>
      <div class="form-group">
        <label for="todoStatus">状态</label>
        <select id="todoStatus" required>
          <option value="未完成">未完成</option>
          <option value="进行中">进行中</option>
          <option value="已完成">已完成</option>
        </select>
      </div>
      <div class="form-group">
        <label for="todoDueDate">截止日期</label>
        <input type="datetime-local" id="todoDueDate" required>
      </div>
      <div class="modal-actions">
        <button type="button" class="btn btn-secondary" onclick="closeTodoModal()">取消</button>
        <button type="submit" class="btn btn-primary">保存</button>
      </div>
    </form>
  </div>
</div>

<script>
    let currentAdmin = null;
    let users = [];
    let todos = [];
    let admins = [];
    let editingUserId = null;
    let editingAdminId = null;
    let editingTodoId = null;

    // 页面加载时检查登录状态
    document.addEventListener('DOMContentLoaded', function() {
        checkLoginStatus();
        loadDashboardData();
    });

    function checkLoginStatus() {
        const adminStr = localStorage.getItem('adminInfo');
        const userType = localStorage.getItem('userType');

        if (!adminStr || userType !== 'admin') {
            window.location.href = 'login.html';
            return;
        }

        currentAdmin = JSON.parse(adminStr);
        if (!currentAdmin.adminName) {
            alert('管理员信息异常，请重新登录或联系管理员');
            localStorage.removeItem('adminInfo');
            localStorage.removeItem('userType');
            window.location.href = 'login.html';
            return;
        }
        document.getElementById('adminName').textContent = `欢迎，${currentAdmin.adminName}`;
    }

    async function loadDashboardData() {
        await Promise.all([
            loadUsers(),
            loadTodos(),
            loadAdmins()
        ]);
        updateDashboard();
    }

    async function loadUsers() {
        try {
            const response = await fetch('/api/admin/users');
            if (response.ok) {
                users = await response.json();
                renderUsers();
            }
        } catch (error) {
            console.error('加载用户数据错误:', error);
        }
    }

    async function loadTodos() {
        try {
            const response = await fetch('/api/todos');
            if (response.ok) {
                todos = await response.json();
                renderTodos();
            }
        } catch (error) {
            console.error('加载待办事项数据错误:', error);
        }
    }

    async function loadAdmins() {
        try {
            const response = await fetch('/api/admin/admins');
            if (response.ok) {
                admins = await response.json();
                renderAdmins();
            }
        } catch (error) {
            console.error('加载管理员数据错误:', error);
        }
    }

    function updateDashboard() {
        document.getElementById('totalUsers').textContent = users.length;
        document.getElementById('totalTodos').textContent = todos.length;
        document.getElementById('pendingTodos').textContent = todos.filter(todo => todo.status === '未完成').length;
        document.getElementById('totalAdmins').textContent = admins.length;
    }

    function switchTab(tabName) {
        // 隐藏所有标签页
        document.querySelectorAll('.tab-pane').forEach(tab => {
            tab.classList.remove('active');
        });

        // 移除所有标签的active类
        document.querySelectorAll('.nav-tab').forEach(tab => {
            tab.classList.remove('active');
        });

        // 显示选中的标签页
        document.getElementById(tabName).classList.add('active');

        // 激活选中的标签
        event.target.classList.add('active');
    }

    function renderUsers() {
        const tbody = document.getElementById('userTableBody');
        tbody.innerHTML = users.map(user => `
                <tr>
                    <td>${user.userId}</td>
                    <td>${user.username}</td>
                    <td>${user.createdAt ? new Date(user.createdAt).toLocaleString() : 'N/A'}</td>
                    <td>
                        <button class="action-btn edit-btn" onclick="editUser(${user.userId})">编辑</button>
                        <button class="action-btn delete-btn" onclick="deleteUser(${user.userId})">删除</button>
                    </td>
                </tr>
            `).join('');
    }

    function renderTodos() {
        const tbody = document.getElementById('todoTableBody');
        tbody.innerHTML = todos.map(todo => `
                <tr>
                    <td>${todo.todoId}</td>
                    <td>${todo.title}</td>
                    <td>${todo.content ? todo.content.substring(0, 50) + '...' : ''}</td>
                    <td><span class="status-badge ${todo.status === '已完成' ? 'status-completed' : 'status-pending'}">${todo.status}</span></td>
                    <td>${todo.user ? todo.user.username : 'N/A'}</td>
                    <td>${new Date(todo.createTime).toLocaleString()}</td>
                    <td>${new Date(todo.dueDate).toLocaleString()}</td>
                    <td>
                        <button class="action-btn edit-btn" onclick="editTodo(${todo.todoId})">编辑</button>
                        <button class="action-btn delete-btn" onclick="deleteTodo(${todo.todoId})">删除</button>
                    </td>
                </tr>
            `).join('');
    }

    function renderAdmins() {
        const tbody = document.getElementById('adminTableBody');
        tbody.innerHTML = admins.map(admin => `
                <tr>
                    <td>${admin.adminId}</td>
                    <td>${admin.adminName}</td>
                    <td>${admin.createdAt ? new Date(admin.createdAt).toLocaleString() : 'N/A'}</td>
                    <td>
                        <button class="action-btn edit-btn" onclick="editAdmin(${admin.adminId})">编辑</button>
                        <button class="action-btn delete-btn" onclick="deleteAdmin(${admin.adminId})">删除</button>
                    </td>
                </tr>
            `).join('');
    }

    function filterUsers() {
        const searchTerm = document.getElementById('userSearch').value.toLowerCase();
        const filteredUsers = users.filter(user =>
            user.username.toLowerCase().includes(searchTerm)
        );

        const tbody = document.getElementById('userTableBody');
        tbody.innerHTML = filteredUsers.map(user => `
                <tr>
                    <td>${user.userId}</td>
                    <td>${user.username}</td>
                    <td>${user.createdAt ? new Date(user.createdAt).toLocaleString() : 'N/A'}</td>
                    <td>
                        <button class="action-btn edit-btn" onclick="editUser(${user.userId})">编辑</button>
                        <button class="action-btn delete-btn" onclick="deleteUser(${user.userId})">删除</button>
                    </td>
                </tr>
            `).join('');
    }

    function filterTodos() {
        const searchTerm = document.getElementById('todoSearch').value.toLowerCase();
        const statusFilter = document.getElementById('todoStatusFilter').value;

        let filteredTodos = todos;

        if (statusFilter) {
            filteredTodos = filteredTodos.filter(todo => todo.status === statusFilter);
        }

        if (searchTerm) {
            filteredTodos = filteredTodos.filter(todo =>
                todo.title.toLowerCase().includes(searchTerm) ||
                todo.content.toLowerCase().includes(searchTerm)
            );
        }

        const tbody = document.getElementById('todoTableBody');
        tbody.innerHTML = filteredTodos.map(todo => `
                <tr>
                    <td>${todo.todoId}</td>
                    <td>${todo.title}</td>
                    <td>${todo.content ? todo.content.substring(0, 50) + '...' : ''}</td>
                    <td><span class="status-badge ${todo.status === '已完成' ? 'status-completed' : 'status-pending'}">${todo.status}</span></td>
                    <td>${todo.user ? todo.user.username : 'N/A'}</td>
                    <td>${new Date(todo.createTime).toLocaleString()}</td>
                    <td>${new Date(todo.dueDate).toLocaleString()}</td>
                    <td>
                        <button class="action-btn edit-btn" onclick="editTodo(${todo.todoId})">编辑</button>
                        <button class="action-btn delete-btn" onclick="deleteTodo(${todo.todoId})">删除</button>
                    </td>
                </tr>
            `).join('');
    }

    // 用户管理功能
    function openUserModal() {
        editingUserId = null;
        document.getElementById('userModalTitle').textContent = '添加用户';
        document.getElementById('userForm').reset();
        document.getElementById('userModal').style.display = 'block';
    }

    function closeUserModal() {
        document.getElementById('userModal').style.display = 'none';
        editingUserId = null;
    }

    function editUser(userId) {
        const user = users.find(u => u.userId === userId);
        if (!user) return;

        editingUserId = userId;
        document.getElementById('userModalTitle').textContent = '编辑用户';
        document.getElementById('username').value = user.username;
        document.getElementById('password').value = '';
        document.getElementById('userModal').style.display = 'block';
    }

    async function deleteUser(userId) {
        if (!confirm('确定要删除这个用户吗？')) return;

        try {
            const response = await fetch(`/api/admin/users/${userId}`, {
                method: 'DELETE'
            });

            if (response.ok) {
                loadUsers();
                updateDashboard();
            } else {
                alert('删除失败，请重试');
            }
        } catch (error) {
            console.error('删除用户错误:', error);
            alert('删除失败，请重试');
        }
    }

    // 管理员管理功能
    function openAdminModal() {
        editingAdminId = null;
        document.getElementById('adminModalTitle').textContent = '添加管理员';
        document.getElementById('adminForm').reset();
        document.getElementById('adminModal').style.display = 'block';
    }

    function closeAdminModal() {
        document.getElementById('adminModal').style.display = 'none';
        editingAdminId = null;
    }

    function editAdmin(adminId) {
        const admin = admins.find(a => a.adminId === adminId);
        if (!admin) return;

        editingAdminId = adminId;
        document.getElementById('adminModalTitle').textContent = '编辑管理员';
        document.getElementById('adminNameInput').value = admin.adminName;
        document.getElementById('adminPassword').value = '';
        document.getElementById('adminModal').style.display = 'block';
    }

    async function deleteAdmin(adminId) {
        if (!confirm('确定要删除这个管理员吗？')) return;

        try {
            const response = await fetch(`/api/admin/${adminId}`, {
                method: 'DELETE'
            });

            if (response.ok) {
                loadAdmins();
                updateDashboard();
            } else {
                alert('删除失败，请重试');
            }
        } catch (error) {
            console.error('删除管理员错误:', error);
            alert('删除失败，请重试');
        }
    }

    // 待办事项管理功能
    async function editTodo(todoId) {
        const todo = todos.find(t => t.todoId === todoId);
        if (!todo) return;
        editingTodoId = todoId;
        document.getElementById('todoModalTitle').textContent = '编辑待办事项';
        document.getElementById('todoTitle').value = todo.title;
        document.getElementById('todoContent').value = todo.content;
        document.getElementById('todoStatus').value = todo.status;
        // 格式化日期时间
        const dueDate = new Date(todo.dueDate);
        document.getElementById('todoDueDate').value = dueDate.toISOString().slice(0, 16);
        document.getElementById('todoModal').style.display = 'block';
    }

    function closeTodoModal() {
        document.getElementById('todoModal').style.display = 'none';
        editingTodoId = null;
    }

    document.getElementById('todoForm').addEventListener('submit', async function(e) {
        e.preventDefault();
        if (!editingTodoId) return;
        const todo = todos.find(t => t.todoId === editingTodoId);
        if (!todo) return;
        const updatedTodo = {
            ...todo,
            title: document.getElementById('todoTitle').value,
            content: document.getElementById('todoContent').value,
            status: document.getElementById('todoStatus').value,
            dueDate: document.getElementById('todoDueDate').value
        };
        try {
            const response = await fetch(`/api/todos/${editingTodoId}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(updatedTodo)
            });
            if (response.ok) {
                closeTodoModal();
                loadTodos();
                updateDashboard();
            } else {
                alert('保存失败，请重试');
            }
        } catch (error) {
            alert('保存失败，请重试');
        }
    });

    async function deleteTodo(todoId) {
        if (!confirm('确定要删除这个待办事项吗？')) return;

        try {
            const response = await fetch(`/api/todos/${todoId}`, {
                method: 'DELETE'
            });

            if (response.ok) {
                loadTodos();
                updateDashboard();
            } else {
                alert('删除失败，请重试');
            }
        } catch (error) {
            console.error('删除待办事项错误:', error);
            alert('删除失败，请重试');
        }
    }

    // 表单提交处理
    document.getElementById('userForm').addEventListener('submit', async function(e) {
        e.preventDefault();

        const userData = {
            username: document.getElementById('username').value,
            passwordHash: document.getElementById('password').value
        };

        try {
            let response;
            if (editingUserId) {
                userData.userId = editingUserId;
                response = await fetch('/api/admin/users', {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(userData)
                });
            } else {
                response = await fetch('/api/admin/users', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(userData)
                });
            }

            if (response.ok) {
                closeUserModal();
                loadUsers();
                updateDashboard();
            } else {
                alert('操作失败，请重试');
            }
        } catch (error) {
            console.error('保存用户错误:', error);
            alert('操作失败，请重试');
        }
    });

    document.getElementById('adminForm').addEventListener('submit', async function(e) {
        e.preventDefault();

        const adminData = {
            adminName: document.getElementById('adminNameInput').value,
            passwordHash: document.getElementById('adminPassword').value
        };

        try {
            let response;
            if (editingAdminId) {
                adminData.adminId = editingAdminId;
                response = await fetch('/api/admin', {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(adminData)
                });
            } else {
                response = await fetch('/api/admin', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(adminData)
                });
            }

            if (response.ok) {
                closeAdminModal();
                loadAdmins();
                updateDashboard();
            } else {
                alert('操作失败，请重试');
            }
        } catch (error) {
            console.error('保存管理员错误:', error);
            alert('操作失败，请重试');
        }
    });

    function logout() {
        localStorage.removeItem('adminInfo');
        localStorage.removeItem('userType');
        window.location.href = 'login.html';
    }

    // 点击模态框外部关闭
    window.onclick = function(event) {
        const userModal = document.getElementById('userModal');
        const adminModal = document.getElementById('adminModal');
        const todoModal = document.getElementById('todoModal');

        if (event.target === userModal) {
            closeUserModal();
        }
        if (event.target === adminModal) {
            closeAdminModal();
        }
        if (event.target === todoModal) {
            closeTodoModal();
        }
    }
</script>
</body>
</html> 
